<template>
	<div class="chat" >
		 <el-dialog :title="name" 
		 :visible.sync="chatView"
		  width="800px" 
		  custom-class="chatView" 
		  :close-on-click-modal="false">
				<div class="usetInfo">
					<div class="u_chat" id="chats">
						<!-- <el-scrollbar> -->
						<vue-scrollbar class="my-scrollbar" ref="Scrollbar">
							<ul id="chat_record">
								<li :class="['chatCont', { is_active: item.send_id == $g.user_id }]" v-for="(item,index) in userChatMessage" :key="index">
									<div class="chatCont_txt clear">
										<span class="chatCont_g box fl">
											<img :src="BASE_URL+item.send_avatar_path">
										</span>
										<div class="chatCont_bx clear">
											<div class="chatCont_t box" v-html="emoji(item.content)"></div>
											<span class="dataTime">{{getDateDiff(item.create_time)}}</span>
										</div>
									</div>
								</li>
							</ul>
						</vue-scrollbar>
					</div>
					<div class="l_chat">
						<el-input v-model="chatInput"  @keyup.enter.native="sendMessage()" placeholder="输入私信内容…" ></el-input>
						<div class="emoji_ch box">
							<img  @click="emojiOFF()"  src="../../../../public/images/emojim.png" class="emoji_icon">
							<vueEmoji class="vueEmoji"	@select="selectEmoji" v-if="showEmoji"></vueEmoji>
						</div>
						<el-button type="primary" @click="sendMessage()">发送</el-button>
					</div>
				</div>
		</el-dialog>
	</div>
</template>

<script>

	import vueEmoji from '../base/emoji'
	import VueScrollbar from 'vue2-scrollbar';
	require("vue2-scrollbar/dist/style/vue2-scrollbar.css")
	export default{
		components: {VueScrollbar, vueEmoji},
		// props: [zxc],
		data(){
			return {
				chatInput: '',
				chatInputTXT: '',
				currentUserId: 0,
				userChatList: [],
				userChatMessage: [],
				temp_userChatList:null,
				temp_currentUserId:0,
				path: null,
				ws: null,
				chatView: false,
				showEmoji: false,
				name: '',
			}
		},
		mounted(){
			// console.log(this.show)
			this.$nextTick(function () {
			    	// 代码保证 this.$el 在 document 中
			    	this.getUserChatList()
			    	this.websocket()
			})
		},
		methods:{
			selectEmoji (code) {
				this.showEmoji = false
				this.chatInput += code
			},
			emojiOFF(){
				this.showEmoji = !this.showEmoji
			},
			getDateTimeStamp (dateStr) {
			    return Date.parse(dateStr.replace(/-/gi,"/"));
			},
			getDateDiff (dateStr) {
			    var publishTime = this.getDateTimeStamp(dateStr)/1000,
			        d_seconds,
			        d_minutes,
			        d_hours,
			        d_days,
			        timeNow = parseInt(new Date().getTime()/1000),
			        d,

			        date = new Date(publishTime*1000),
			        Y = date.getFullYear(),
			        M = date.getMonth() + 1,
			        D = date.getDate(),
			        H = date.getHours(),
			        m = date.getMinutes(),
			        s = date.getSeconds();
			        //小于10的在前面补0
			        if (M < 10) {
			            M = '0' + M;
			        }
			        if (D < 10) {
			            D = '0' + D;
			        }
			        if (H < 10) {
			            H = '0' + H;
			        }
			        if (m < 10) {
			            m = '0' + m;
			        }
			        if (s < 10) {
			            s = '0' + s;
			        }

			    d = timeNow - publishTime;
			    d_days = parseInt(d/86400);
			    d_hours = parseInt(d/3600);
			    d_minutes = parseInt(d/60);
			    d_seconds = parseInt(d);

			    if(d_days > 0 && d_days < 3){
			        return d_days + '天前';
			    }else if(d_days <= 0 && d_hours > 0){
			        return d_hours + '小时前';
			    }else if(d_hours <= 0 && d_minutes > 0){
			        return d_minutes + '分钟前';
			    }else if (d_seconds < 60) {
			        if (d_seconds <= 0) {
			            return '刚刚';
			        }else {
			            return d_seconds + '秒前';
			        }
			    }else if (d_days >= 3 && d_days < 30){
			        return M + '-' + D + ' ' + H + ':' + m;
			    }else if (d_days >= 30) {
			        // return Y + '-' + M + '-' + D + ' ' + H + ':' + m;
			        return M + '-' + D + ' ' + H + ':' + m;
			    }
			},
			//滚动条
			someMethod() {

				this.$nextTick(function () {
					if (this.currentUserId && document.getElementById('chat_record') ) {
						let h = document.getElementById('chat_record').clientHeight
						this.$refs.Scrollbar.scrollToY(h)
					}    
				})			   
			},
			//聊天记录
			getUserChatList() {
				let success = (res => {		
					let _this = this
					this.userChatList = deep_clone(res.data);
					this.currentUserId = 0;
					this.temp_userChatList = this.$store.getters.send_userinfo

					if (this.temp_userChatList != null) {

						let flag = false;
						this.userChatList.forEach(function(item, i) {
							if (item.send_id == _this.temp_userChatList.send_id) {	
								flag = true;
								return;
							}
						})
						!flag && this.userChatList.push({
							send_id : this.temp_userChatList.send_id,
							avatar_path : this.temp_userChatList.avatar_path,
							username:this.temp_userChatList.username
						});

						this.currentUserId = this.temp_userChatList.send_id;
						// _this.getUserChatOne(this.currentUserId);
					}
					
					
				})
				let success1 = (res => {
					console.log(res)
				})
				this.$ajax({
					url: '/api/user/user_chat_list',
					params: {
						user_id: this.$g.user_id
					},
					func:{
						success:success
					}
				})
			},
			//发送信息
			sendMessage() {
				if (this.chatInput == '' && this.chatInputTXT == '') {
					return;
				}
				// let content = 
				let message = JSON.stringify({
					type: 'say',
					to_client_id: this.currentUserId,
					content: this.emoji(this.chatInput)
				})
				// console.log('发送数据...:', message)
				this.ws.send(message)

				this.chatInput = ''
				this.chatInputTXT = ''
			},
			websocket() {
				let webSocketChatURL = sessionStorage.getItem('user_chat_url');
				this.ws = new WebSocket(webSocketChatURL)
				this.ws.onopen = () => {
					var message = JSON.stringify({
						type: 'login',
						uid: this.$g.user_id == '' ? this.$route.query.id : this.$g.user_id
					})
					this.ws.send(message)
					// Web Socket 已连接上，使用 send() 方法发送数据
					console.log('已连接上...,发送身份信息：' + message)
				}
				this.ws.onmessage = evt => {
					var data = JSON.parse(evt.data);
					if (data.status == 'success') {
						var type = data.type
						var data = data.data
						var flag = false;

						// console.log(data[0].send_id, data[0].receive_id, this.currentUserId, type);
						if (type == 'send') {
							if (data[0].receive_id == this.currentUserId) { // 当前聊天用户，直接追加数组
								this.userChatMessage.push(data[0])
							}

							this.userChatList.forEach(function(item, i) {
								if (item.send_id == data[0].receive_id) {
									item.content = data[0].content;
									flag = true;
									return;
								}

							})
						} else if (type == 'receive') {

							if (data[0].send_id == this.currentUserId) { // 当前聊天用户，直接追加数组
								this.userChatMessage.push(data[0])
							}
							var _this = this;
							this.userChatList.forEach(function(item, i) {
								if (item.send_id == data[0].send_id) {
									item.content = data[0].content
									if( item.send_id == _this.currentUserId ){
										item.read_data = '已读'
									}else{
										item.read_data = '未读'
									}
									
									flag = true;
									return;
								}
							})

						} else {
							flag = true;
						}
						
						this.someMethod()

						if (!flag) {
							this.userChatList.unshift({
								avatar_path: data[0].send_avatar_path,
								content: data[0].content,
								create_time: data[0].create_time,
								//read_data : "未读",
								receive_id: data[0].receive_id,
								send_id: data[0].send_id,
								//sum_data : 26,
								time: data[0].create_time,
								username: data[0].send_name
							})
						}

					}

					console.log('数据已接收...:', data)
				}
				this.ws.onclose = function() {
					// 关闭 websocket
					console.log('连接已关闭...')
				}
				// 组件销毁时调用，中断websocket链接
				this.over = () => {
					this.ws.close()
				}
			},
			getUserChatOne(obj) {
				let msg = deep_clone(obj)
				console.info(msg)
				this.chatView = true
				this.name  = msg.name
				this.userChatList.forEach(function(item, i) {
					if (item.send_id == msg.id) {
						item.read_data = '已读'
						return;
					}
				})

				let success = (res => {		
					this.userChatMessage = res.data;
					this.currentUserId = msg.id;
					this.someMethod()
				})
				this.$ajax({
					url: '/api/user/user_chat',
					params: {
						sr_1: msg.id,
						sr_2:  this.$g.user_id,
						update_read: 1,
						orderby:'time',
						orderby_desc:'asc'
					},
					func:{
						success:success
					}
				})
			},
		}
	}
</script>  

<style lang="scss">
	.chatView{
		.el-dialog__header{
			background: #338efc;
			color: #fff;
			.el-dialog__title,
			.el-dialog__close{
				color: #fff;
				font-size: 16px;
			}
		}
		.el-dialog__body{
			height: 680px;
			padding: 0;
		}

		.usetInfo{
			height: 100%;
		}

		.l_chat{
			text-align: center;
			text-align-last: justify;
			padding: 15px 25px;
			border-top: 1px solid #DDDDDD;
			position: relative;
			>div,
			>span
			>button{
				text-align: left;
				text-align-last: justify;
				display: inline-block;
				vertical-align: top;
			}
			>.el-input{
				width: 600px;
				>input{
					height: 36px;
					line-height: 36px;
				}
			}
			>button{
				padding: 10px 20px;
			}
			.emoji_icon{
				width: 25px;
				height: 25px;
				cursor: pointer;
				margin-top: 4px;
			}
		}
		.u_chat{
			height: 90%;
			ul{
				padding: 0 30px;
				>li{
					padding-top: 25px;
				}
			}
		}

		.my-scrollbar {
		    height: 100%;
		}
		.chatCont{
			padding-top: 25px;
			&:last-of-type{
				padding-bottom: 25px;
			}
		}
		.chatCont {
		    padding-top: 25px;
		}
		.emoji_ch{
			margin: 0 25px;
		}
		.chatCont_txt{
			position: relative;
			>span{
				width: 40px;
				height: 40px;
				border-radius: 50%;
				overflow: hidden;
				background: #effaff;
				line-height: 40px;
				text-align: center;
				color: #fff;
				>img{
					width: 100%;
					height: 100%;
				}

			}
			.chatCont_t{
				max-width: 60%;
				word-wrap: break-word;
				word-break: break-all;
				padding: 10px 20px;
				font-size: 14px;
				line-height: 21px;
				background: #F8F8F8;
				border-radius: 3px;
				position: relative;
				margin-left: 25px;
				box-shadow: 0 1px 1px 0 rgba(0, 0, 0, 0.1);
				&:before{
					content: " ";
					display:inline-block;
					width:0;
					height:0;
					overflow:hidden;
					line-height:0;
					font-size:0;
					vertical-align:middle;
					border-right:7px solid #F8F8F8;
					border-left:0 none;
					border-top:7px solid transparent;
					border-bottom:7px solid transparent;
					position: absolute;
					left: -7px;
				}
			}
			.dataTime{
				color: #999;
				display: inline-block;
				margin: 10px;
				font-size: 12px;
			}
		}

		.is_active{
			.chatCont_txt{
				span{
					float: none;
					float: right;
				}
				.chatCont_t{
					float: none;
					float: right;
					margin: 0 25px 0 0;
					background: #BCDBFF;
					&:before{
						left: initial;
						right: -7px;
						border-left:7px solid #BCDBFF;
						border-right:0 none;
						border-top:7px solid transparent;
						border-bottom:7px solid transparent;
					}
				}
			}
			.chatCont_t{
				border: 0;
			}
		}

	}

	.emoji {
	  width: 380px;
	  height: 186px;
	  bottom: 30px;
	  background: #fff;
	  z-index: 10;
	  padding: 10px;
	  margin-right: 10px;
	  .emoji-controller {
	    height: 36px;
	    overflow: hidden;
	    margin-bottom: 0;
	    li {
	      float: left;
	      width: 76px;
	      font-size: 12px;
	      line-height: 36px;
	      cursor: pointer;
	      text-align: center;
	      position: relative;
	      text-align-last: initial;
	      &.active::after{
	        content: '';
	        width: 100%;
	        height: 1px;
	        background: #0689dd;
	        left: 0;
	        bottom: 4px;
	        position: absolute;
	      }
	    }
	  }
	  .emoji-container {
	    height: 140px;
	    overflow-y: auto;
	    overflow-x: hidden;
	    position: relative;
	    li {
	      font-size: 0;
	      padding: 5px;
	      a {
	        float: left;
	        overflow: hidden;
	        height: 35px;
	        transition: all ease-out .2s;
	        border-radius: 4px;
	        &:hover {
	          background-color: #d8d8d8;
	          border-color: #d8d8d8;
	        }
	        span {
	          width: 25px;
	          height: 25px;
	          display: inline-block;
	          border: 1px solid transparent;
	          cursor: pointer;
	        }
	      }
	    }
	  }
	}



	.vueEmoji{
		position: absolute;
		right: 0;
		top: -207px;
		margin: 0;
		box-shadow: 0 6px 7px 0 rgba(0,0,0,0.10);
	}


</style>